<template>
  <div id="map" className="map">

  </div>
</template>

<script>
import { listPark } from '../../api/system/park'

window._AMapSecurityConfig = {
  securityJsCode: '652541c3a3d61db3cfc900ffa7d9e124'
}

import AMapLoader from '@amap/amap-jsapi-loader'
import $ from 'jquery'
import { colors } from '../../utils/mapSettings'
import { citys, citys2 } from '../../utils/citys'
import store from '../../store'

export default {
  name: 'Map3',
  props: {
    showPosition: Function,
    editAreaData:Function,
    myForm:Object,
    //当前form id
    id:{
      type:Number,
      default:0
    },
  },
  data() {
    return {
      //当前是否为城市
      isCity: false,
      //地图模块
      map: null,
      //地图显示模块
      district: null,
      polygon: null,
      polygon2: null,
      //多边形列表
      polygon3: [],
      //绘制地图
      districtExplorer: null,
      //文本标记
      text: 'null',
      outClick: null,
      //点标记
      marker: null,
      //默认城市 --- 重庆
      autoComplete: null,
      //切换区域
      switch2AreaNode: null,
      //格式化地图
      formateMap: null,
      //记录当前搜索的名称
      searchName: '',
      textList: [],
      mouseTool:null,
      parkData:[],
      //根据城市查询园区数据
      parksList:[],
      //是否已经绘制
      isDraw:false,
      //当前的多边形
      currentPolygon:null,
      //编辑的多边形
      polyEditor:null,
      //Amap  对象
      Amap:null,
      //绘制的区域数组
      pathArray1:[],
    }
  },
  components: {},

  created() {
    if (this.$route.query.cityName) {
      this.isCity = true
    }
  },
  mounted() {
    this.mapInit()
  },
  methods: {
    //编辑进入对应城市
    cdCurrentCity(cityCode){
      this.$nextTick(()=>{
        setTimeout(()=>{
          this.outClick()
          this.isCity = true
          this.switch2AreaNode(cityCode)
          this.showPolygon()
        },1000)
      })
    },
    //重新绘制当前多边形
    reSetPolygon(){
      let polygon = null
      this.isDraw = false
      this.polygon3.forEach((item,index) =>{
        console.log(index,"index")
        if(item.getExtData().id == this.id){
          polygon = {
            item,index
          }
        }
      })
      console.log(polygon,"polygonpolygonpolygon")
      //编辑进入 点击重新绘制
      if(polygon){
        this.polygon3.splice(polygon.index ,1)
        this.map.remove(polygon.item)
      }
      if(this.currentPolygon){
        this.map.remove(this.currentPolygon)
      }

      console.log(this.polygon3,"this.polygon3222222")
    },
    //清空所有多边形
    clearAllPolygon(){
      this.polygon3.forEach((item,index) =>{
        this.map.remove(item)
      })
    },
    //渲染 多边形
    showPolygon(cityCode){
      listPark({cityCode}).then(res => {
        this.parksList = res.rows.map(item => {
          if(this.id == item.id){
            this.isDraw = true
          }
          return {
            id:item.id,
            color:item.parkColor,
            borderColor:item.borderColor,
            path:JSON.parse(item.parkData)
          }
        })
        console.log( this.parksList," this.parksList")
        //生成产业园区列表
        this.parksList.forEach(item => {
          var temporaryPolygon = new AMap.Polygon({
            path: item.path,
            fillColor: item.color, // 多边形填充颜色
            borderWeight: 0.2, // 线条宽度，默认为 1
            strokeColor: item.borderColor, // 线条颜色
            fillOpacity:0.3,
            extData:{
              id:item.id
            }
          })
          this.polygon3.push(temporaryPolygon)
          if(item.id == this.id){
            this.currentPolygon = temporaryPolygon
            this.pathArray1 = item.path
            this.map.setFitView([this.currentPolygon ])
          }
        })
        this.polygon3.forEach(item=>{
          this.map.add(item);
        })
        console.log(this.polygon3,"this.polygon3this.polygon3this.polygon3初始化")

      })
    },
    //绘制多边形
    drawPolygon() {
      var that = this
      if(!this.isDraw){
        this.map.setStatus({
          dragEnable: false,
        })
        this.mouseTool.polygon({
          strokeColor: this.myForm.borderColor,
          strokeOpacity: 1,
          strokeWeight: 2,
          borderWeight: 0.2,
          fillColor: this.myForm.parkColor,
          draggable:true,
          fillOpacity: 0.4,
          zIndex:999999999,
          strokeStyle: "solid",
        });
      }else{
        this.$message.error("区域不能重复绘制！")
      }
      this.mouseTool.on('draw', (event) => {
        console.log(event,"eventevent")
        // event.obj 为绘制出来的覆盖物对象
        this.pathArray1 = event.obj.De.path.map(item => {
          return [item.lng,item.lat]
        })
        this.isDraw = true
        this.map.setStatus({
          dragEnable: true,
        })
        that.editAreaData(this.pathArray1)
      })
    },
    //将绘制的图形 删除 重新绘制
    changePolygon(){
      if(this.currentPolygon){
        this.map.remove(this.currentPolygon)
      }
      console.log(this.pathArray1,"this.pathArray1")
      if(this.pathArray1.length > 0){
        this.currentPolygon = new AMap.Polygon({
          path: this.pathArray1,
          fillColor: this.myForm.parkColor, // 多边形填充颜色
          borderWeight: 0.2, // 线条宽度，默认为 1
          strokeColor: this.myForm.borderColor, // 线条颜色
          fillOpacity:0.4,
          extData:{
            id:this.id
          }
        })
        this.clearPolygon()
        this.map.add(this.currentPolygon)
      }
    },
    //编辑多边形
    editPolygon(flag){
      var that = this
      console.log("-----------")
      //当前未 产生区域多边形时 直接返回


      this.map.plugin(['AMap.PolyEditor'],()=>{
        // if(this.pathArray1.length > 0){
        //   console.log(this.pathArray1,"pathArray1")
        //   this.currentPolygon = new AMap.Polygon({
        //     path: this.pathArray1,
        //     fillColor: this.myForm.parkColor, // 多边形填充颜色
        //     borderWeight: 0.2, // 线条宽度，默认为 1
        //     strokeColor: 'red', // 线条颜色
        //     fillOpacity:0.4,
        //     extData:{
        //       id:this.id
        //     }
        //   })
        //   this.clearPolygon()
        //   this.map.add(this.currentPolygon)
        // }
        this.changePolygon()
        if(!this.currentPolygon)return

        this.polyEditor = new this.Amap.PolyEditor(this.map, this.currentPolygon)
        //当直接改变颜色时
        this.polyEditor.open()
        this.polyEditor.on('end', function(event) {
          console.log(event,"event.target")
          this.pathArray1 = event.target.De.path.map(item => {
            return [item.lng,item.lat]
          })
          that.editAreaData(this.pathArray1)
        })
      })
    },
    //取消编辑
    downEditPolygon(){
      this.polyEditor.close()
    },
    //删除多边形
    clearPolygon(){
      // this.pathArray1 = []
      this.isDraw = false
      this.mouseTool.close(true)
    },
    backHome() {
      this.outClick()
    },
    // 初始加载底图
    mapInit: function() {
      var that = this
      AMapLoader.load({
        key: '7060e76c7045c8344955f5e4e649dc01',
        // 插件集合
        plugin: ['AMap.DistrictSearch', 'AMap.ControlBar','AMap.MouseTool','AMap.PolyEditor'],
        v: '1.4.15',
        // protocol:"",
        AMapUI: {
          version: '1.1',
          plugins: ['overlay/SimpleMarker']
        },
        uiVersion: '2.0' //添加 uiVersion 的脚本版本号
      }).then((AMap) => {
        this.Amap = AMap
        that.map = new AMap.Map('map', {
          center: [106.549509, 29.560767], // [107.755852, 29.590834],
          expandZoomRange: true,
          cursor: 'pointer',
          // zooms: [3, 20],
          dragEnable: true, //拖拽
          zoomEnable: true,  //缩放
          zoom: 5, //8.35,
          pitch: 0, // 地图俯仰角度，有效范围 0 度- 83 度
          viewMode: '3D', // 地图模式
          mapStyle: 'amap://styles/ca9c387f36280f589fc4bd06c9cfcac7' // "amap://styles/cf4bbeff185671422895aaff7434766a"
        })
        AMap.plugin(['AMap.MouseTool'],()=>{
          that.mouseTool = new AMap.MouseTool(that.map);
        })
        that.map.on('zoomchange', function() {
          var zoom = that.map.getZoom() //获取当前地图级别
          if (zoom < 7.5) {
            that.map.setZoom(7.5)
            that.map.setCenter([107.829509, 30.160967])
          }
        })
        // 初始化地图名称显示
        that.showCityName()
        if (that.isCity || that.isDetail) {
          that.clearCityName()
        }
        that.map.on('zoomchange', function() {
          if (that.isCity) {
            return false
          }
          if (that.map.getZoom() <= 9) {
            that.clearCityName()
            that.showCityName()
          } else {
            that.showCityName2()
          }
        })//缩放变化
        /**
         *绘制 重庆区域
         * */
        function showCityAll(){
          //main.js加载的模块 DistrictSearch
          AMap.plugin(['AMap.DistrictSearch'], () => {
            // 行政区查询服务
            that.district = new AMap.DistrictSearch({
              subdistrict: 0,
              extensions: 'all',
              level: 'city'
            })

            /**
             * 只显示当前行政区域
             * */
            if (that.polygon2) {
              that.map.remove(that.polygon2)
            }
            //绘制地图，只显示当前行政区域，自定义边境颜色
            that.district.search('重庆', (status, result) => {
              // 外多边形坐标数组和内多边形坐标数组
              var outer = [
                new AMap.LngLat(-360, 90, true),
                new AMap.LngLat(-360, -90, true),
                new AMap.LngLat(360, -90, true),
                new AMap.LngLat(360, 90, true)
              ]
              var holes = result.districtList[0].boundaries
              var pathArray = [outer]
              pathArray.push.apply(pathArray, holes)
              that.polygon = new AMap.Polygon({
                pathL: pathArray,
                strokeColor: '#fff',
                strokeWeight: 1.5,
                fillColor: '#fff',
                fillOpacity: 1
              })
              that.polygon.setPath(pathArray)

              that.map.add(that.polygon)
              // that.$emit('loadingSuccess')
            })
          })
        }

        //行政区域操作
        AMapUI.loadUI(['geo/DistrictExplorer'], function(DistrictExplorer) {
          //创建一个实例
          that.districtExplorer = new DistrictExplorer({
            eventSupport: true,
            map: that.map
          })
          /**
           * 全部全部地图
           * */
          //切换区域
          that.switch2AreaNode = function switch2AreaNode (adcode, callback) {
            if (currentAreaNode && ('' + currentAreaNode.getAdcode() === '' + adcode)) {
              return
            }
            loadAreaNode(adcode, function(error, areaNode) {
              if (error) {
                if (callback) {
                  callback(error)
                }
                return
              }
              currentAreaNode = window.currentAreaNode = areaNode
              that.$emit('handleClickRegion', currentAreaNode)
              //设置当前使用的定位用节点
              that.districtExplorer.setAreaNodesForLocating([currentAreaNode])
              refreshAreaNode(areaNode)
              if (callback) {
                callback(null, areaNode)
              }
            })
          }
          that.formateMap =  function formateMap() {
            var adcode = 500000
            that.districtExplorer.loadAreaNode(adcode, function(error, areaNode) {
              //更新地图视野
              that.map.setBounds(areaNode.getBounds(), null, null, true)
              //清除已有的绘制内容
              that.districtExplorer.clearFeaturePolygons()
              //绘制子区域
              that.districtExplorer.renderSubFeatures(areaNode, function(feature, i) {
                var fillColor = colors[i % colors.length]
                // var strokeColor = colors[colors.length - 1 - i % colors.length];
                var strokeColor = colors[i % colors.length]
                return {
                  cursor: 'default',
                  bubble: true,
                  strokeColor: strokeColor, //线颜色
                  strokeOpacity: 1, //线透明度
                  strokeWeight: 1, //线宽
                  fillColor: fillColor, //填充色
                  fillOpacity: .9 //填充透明度
                }
              })

              //绘制父区域
              that.districtExplorer.renderParentFeature(areaNode, {
                cursor: 'default',
                bubble: true,
                strokeColor: 'black', //线颜色
                strokeOpacity: 1, //线透明度
                strokeWeight: 1, //线宽
                fillColor: null, //填充色
                fillOpacity: 0.5 //填充透明度
              })
              that.map.setZoom(7.5)
            })
          }


          /**
           * 初始化地图
           * */
          that.switch2AreaNode(500000)
          // showCityAll()
          that.formateMap()



          /**
           * 初始化绘制地图
           * */
          //监听feature的hover事件
          that.districtExplorer.on('featureMouseover', function(e, feature) {
            const name = feature.properties.name
            const position = [feature.properties.center[0], feature.properties.center[1]]
            if (!that.isCity) {
              toggleHoverFeature(feature, e.type === 'featureMouseover',
                e.originalEvent ? e.originalEvent.lnglat : null)
              // showCityName(name, position)
            }
          })
          //移出监听feature的事件
          that.districtExplorer.on('featureMouseout', function(e, feature) {
            that.map.remove(that.text)
            if (!that.isCity ) {
              toggleHoverFeature(feature, e.type === 'featureMouseover',
                e.originalEvent ? e.originalEvent.lnglat : null)
            }

          })
          //监听鼠标在feature上滑动
          that.districtExplorer.on('featureMousemove', function(e, feature) {
            //更新提示位置
            tipMarker.setPosition(e.originalEvent.lnglat)
          })

          //feature被点击 内部被点击
          that.districtExplorer.on('featureClick', function(e, feature) {
            var props = feature.properties
            that.$emit("choiceCity",props.adcode,props.name)
            if (that.isCity ) {

            } else {
              that.clearCityName()

              that.showPolygon(props.adcode)
              var props = feature.properties
              that.isCity = true
              //如果存在子节点
              // if (props.childrenNum > 0) {
              //切换聚焦区域
              that.switch2AreaNode(props.adcode)
            }
            // }
          })

          that.outClick = function outClick() {
            that.isCity = false
            that.switch2AreaNode(500000)
            // showCityAll()
            if(that.polygon2){
              that.map.remove(that.polygon2)
            }
            that.formateMap()
          }
          //外部区域被点击
          that.districtExplorer.on('outsideClick', function(e) {
            that.clearAllPolygon()
            that.districtExplorer.locatePosition(e.originalEvent.lnglat, function(error, routeFeatures) {
              if (that.isDetail) {
                return
              }
              if (routeFeatures && routeFeatures.length > 1) {
                //切换到省级区域
                that.outClick()
                //清空当前搜索的区域名称
                that.searchName = null
              } else {
                //切换到全国
                that.switch2AreaNode(100000)
              }
            }, {
              levelLimit: 2
            })
          })

          //当前聚焦的区域
          //当前聚焦的区域
          var currentAreaNode = null
          //鼠标hover提示内容
          var $tipMarkerContent = $('<div class="tipMarker top"></div>')
          var tipMarker = new AMap.Marker({
            content: $tipMarkerContent.get(0),
            offset: new AMap.Pixel(0, 0),
            bubble: true
          })

          //根据Hover状态设置相关样式
          function toggleHoverFeature(feature, isHover, position) {
            tipMarker.setMap(isHover ? that.map : null)
            if (!feature) {
              return
            }
            var props = feature.properties
            if (isHover) {
              //更新提示内容
              $tipMarkerContent.html(' ')
              //更新位置
              tipMarker.setPosition(position || props.center)
            }
            $('#area-tree').find('h2[data-adcode="' + props.adcode + '"]').toggleClass('hover', isHover)
            //更新相关多边形的样式
            var polys = that.districtExplorer.findFeaturePolygonsByAdcode(props.adcode)
            for (var i = 0, len = polys.length; i < len; i++) {
              polys[i].setOptions({
                fillOpacity: isHover ? 0.6 : 0.9
              })
            }
          }

          //绘制某个区域的边界
          function renderAreaPolygons(areaNode) {
            //更新地图视野
            that.map.setBounds(areaNode.getBounds(), null, null, true)
            //清除已有的绘制内容
            that.districtExplorer.clearFeaturePolygons()
            let adcode = areaNode._data.geoData.parent.properties.adcode
            if (adcode == '500000') {
              return
            }
            AMap.plugin(['AMap.DistrictSearch'], () => {
              // 行政区查询服务
              var district = new AMap.DistrictSearch({
                subdistrict: 0,
                extensions: 'all',
                level: 'biz_area'
              })
              //绘制地图，只显示当前行政区域，自定义边境颜色
              district.search(adcode.toString(), (status, result) => {
                // 外多边形坐标数组和内多边形坐标数组
                var outer = [
                  new AMap.LngLat(-360, 90, true),
                  new AMap.LngLat(-360, -90, true),
                  new AMap.LngLat(360, -90, true),
                  new AMap.LngLat(360, 90, true)
                ]
                var holes = result.districtList[0].boundaries
                var pathArray = [outer]
                pathArray.push.apply(pathArray, holes)

                that.polygon2 = new AMap.Polygon({
                  pathL: pathArray,
                  strokeColor: '#0469c1',
                  strokeWeight: 1.5,
                  fillColor: '#123553',
                  fillOpacity: .9,
                  bubble: true
                })
                that.polygon2.setPath(pathArray)
                that.map.add(that.polygon2)
              })
            })
          }

          //切换区域后刷新显示内容
          function refreshAreaNode(areaNode) {
            that.districtExplorer.setHoverFeature(null)
            renderAreaPolygons(areaNode)
          }


          //加载区域
          function loadAreaNode(adcode, callback) {
            that.districtExplorer.loadAreaNode(adcode, function(error, areaNode) {
              if (error) {
                if (callback) {
                  callback(error)
                }
                return
              }
              // renderAreaPanel(areaNode);
              if (callback) {
                callback(null, areaNode)
              }
            })
          }

        })

      }).catch(e => {
        console.log(e)
      })
    },


    //清除所有城市的名称
    clearCityName() {
      this.textList.forEach((item, index) => {
        this.map.remove(this.textList[index])
      })
    },
    //1。不显示被隐藏的城市名称
    showCityName() {
      //只有下面这些城市需要缩放到一定层级才显示城市名称
      citys.forEach((item, index) => {
        this.textList.push(new AMap.Text({
          text: item.name,
          anchor: 'center', // 设置文本标记锚点
          style: {
            'background-color': 'rgba(0,0,0,0)',
            'border-width': 0,
            'text-align': 'center',
            'font-size': '14px',
            'color': '#000'
          },
          bubble: true,
          position: item.position
        }))
        this.textList[this.textList.length - 1].setMap(null)
        this.textList[this.textList.length - 1].setMap(this.map)
      })
    },
    //2。显示被隐藏的城市名称
    showCityName2() {
      let citys1 = citys.concat(citys2)
      citys1.forEach((item, index) => {
        this.textList.push(new AMap.Text({
          text: item.name,
          anchor: 'center', // 设置文本标记锚点
          style: {
            'background-color': 'rgba(0,0,0,0)',
            'border-width': 0,
            'text-align': 'center',
            'font-size': '14px',
            'color': '#000'
          },
          bubble: true,
          position: item.position
        }))
        this.textList[this.textList.length - 1].setMap(null)
        this.textList[this.textList.length - 1].setMap(this.map)
      })
    },
  },
  map3Form: {
    get() {
      return this.$store.state.map3.form
    },
    set(val) {
      this.$store.commit("SET_FORM",val)
    }
  },
}
</script>
<style>

</style>
<style lang="scss">


.amap-logo {
  display: none;
  opacity: 0 !important;
}

.amap-copyright {
  opacity: 0;
}


.tipMarker {
  display: flex;
  background: #fff;
}
</style>
